<?php

namespace App\Http\Controllers\Admin;

use App\Admin_authority;
use App\Admin_classify;
use App\Admin_role;
use App\Admin_role_authority;
use App\Admin_user_role;
use App\Common;
use Illuminate\Http\Request;
use App\Admin_user;
use App\Admin_module;
use App\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SystemController extends AController
{

    //管理员列表
    public function administrator($request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $wh = [
            ['u.status','<>','2']
        ];

        $start_time = '';
        if(isset($request['start_time']) && !empty($request['start_time'])){
            $start_time = strtotime($request['start_time']);
            $wh[] = ['u.created_at','>=',$start_time];
            $start_time = date('Y-m-d',$start_time);
        }

        $end_time = '';
        if(isset($request['end_time']) && !empty($request['end_time'])){
            $end_time = strtotime($request['end_time']);
            $wh[] = ['u.created_at','<=',$end_time];
            $end_time = date('Y-m-d',$end_time);
        }

        $username = '';
        if(isset($request['username']) && !empty($request['username'])){
            $username = (string)$request['username'];
            $wh[] = ['u.nickname','like',"%$username%"];
        }

        $list = Admin_user::from('admin_user as u')
            ->where($wh)
            ->leftjoin('admin_user_role as z','z.user_id','=','u.id')
            ->leftjoin('admin_role as r','r.id','=','z.role_id')
            ->select('u.*','r.name as r_name','r.id as r_id')
            ->get();
        return view('Admin.System.administrator', ['list' => $list, 'menu' => __FUNCTION__,'start_time'=>$start_time,'end_time'=>$end_time,'username'=>$username]);
    }

    //添加管理员表单
    public function administrator_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $roles = Admin_role::where('status','=','1')->pluck('name','id');
        return view('Admin.System.administrator_add',['roles'=>$roles]);
    }

    //添加管理员操作
    public function administrator_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            $account = $request->account;
            $nickname = $request->nickname;
            $password = $request->password;
            $repassword = $request->repassword;
            $role_id = $request->role_id;

            if ($password !== $repassword) {
                return false;
            }
            DB::beginTransaction();
            try {
                $model = new Admin_user();
                $model->nickname = $nickname;
                $model->account = $account;
                $model->password = Common::md6($password);
                $return = $model->save();
                if($model->id && $role_id){
                    //添加角色
                    $mod = new Admin_user_role();
                    $mod->role_id = $role_id;
                    $mod->user_id = $model->id;
                    $return = $mod->save();
                }
            } catch (\Exception $e) {
                Log::log('error', $e);
                DB::rollBack();
                return 2;
            }
            DB::commit();
            return (string)$return;
        }
    }

    //管理员修改页面
    public function administrator_edit($id)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $vo = Admin_user::find($id);
        $roles = Admin_role::where('status','=','1')->pluck('name','id');
        return view('Admin.System.administrator_edit',['vo'=>$vo,'roles'=>$roles]);
    }

    //管理员修改操作
    public function administrator_edit_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if($request->ajax()){
            DB::beginTransaction();
            try{
                $id = $request->get('id');
                $model = Admin_user::find($id);
                $model->nickname = $request->get('nickname');
                if($request->get('password') && $request->get('password') == $request->get('repassword')){
                    $model->password = Common::md6($request->get('password'));
                }
                $model->save();
                Admin_user_role::where('user_id','=',$id)->delete();
                if($request->role_id){
                    $mod = new Admin_user_role();
                    $mod->user_id = $id;
                    $mod->role_id = $request->role_id;
                    $mod->save();
                }
                $this->refresh_redis($model->account);
            }catch(\Exception $e){
                Log::log('error',$e);
                DB::rollBack();
                return 0;
            }
            DB::commit();
            return 1;
        }
    }

    //管理员状态修改
    public function administrator_status(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $res = Admin_user::find($request->id);
                $res->status = $request->status;
                $res->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }

    }

    //管理员删除操作
    public function administrator_del(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            $id = $request->id;
            try {
                if(is_array($id)){
                    Admin_user::whereIn('id',$id)->update(['status'=>2]);

                }else{
                    $res = Admin_user::find($request->id);
                    $res->status = 2;
                    $res->save();
                }

            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }

    //系统模块页面
    public function module()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $list = Admin_module::where('status', '<>', '2')->get();
        return view('Admin.System.module', ['list' => $list, 'menu' => __FUNCTION__]);
    }

    //系统模块添加页
    public function module_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        return view('Admin.System.module_add');
    }

    //系统模块添加处理
    public function module_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $model = new Admin_module();
                $model->name = $request->module_name;;
                $model->sort = $request->sort ?: 0;
                $model->icon = $request->icon;
                $return = $model->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 2;
            }
            return (string)$return;
        }
    }

    //系统模块状态修改
    public function module_status(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $res = Admin_module::find($request->id);
                $res->status = $request->status;
                $res->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            $this->refresh_redis('all');
            return 1;
        }
    }

    //系统模块修改页
    public function module_edit($id)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $res = Admin_module::find($id);
        return view('Admin.System.module_edit', ['vo' => $res]);
    }

    //系统模块修改处理
    public function module_edit_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                if (!$request->id) {
                    return 0;
                }
                $model = Admin_module::find($request->id);
                if ($request->name) {
                    $model->name = $request->name;
                }
                if ($request->icon) {
                    $model->icon = $request->icon;
                }
                if ($request->sort) {
                    $model->sort = $request->sort;
                }
                $model->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }

    //系统模块删除
    public function module_del(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $res = Admin_module::find($request->id);
                $res->status = 2;
                $res->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            $this->refresh_redis('all');
            return 1;
        }
    }

    //分类页面
    public function classify()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }


        $list = Admin_classify::from('admin_classify as c')
            ->where('c.status', '<>', '2')
            ->leftJoin('admin_module as m', 'group_id', '=', 'm.id')
            ->select('c.*', 'm.name as m_name')
            ->get();

        return view('Admin.System.classify', ['list' => $list, 'menu' => __FUNCTION__]);
    }

    //分类添加页面
    public function classify_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $modules = Admin_module::where('status', '<>', '2')->pluck('name', 'id');
        return view('Admin.System.classify_add', ['modules' => $modules]);
    }

    //添加分类操作
    public function classify_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                if (!Admin_module::where('status', '<>', '2')->find($request->group_id)) {
                    return 0;
                }
                $model = new Admin_classify();
                $model->name = $request->classify_name;
                $model->sort = $request->sort ?: 0;
                $model->group_id = $request->group_id;
                $model->route = $request->route;
                $model->func = $request->func;
                $model->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }

    //分类状态修改
    public function classify_status(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }
        if ($request->ajax()) {
            try {
                $res = Admin_classify::find($request->id);
                $res->status = $request->status;
                $res->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }

    //分类修改页面
    public function classify_edit($id)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $res = Admin_classify::find($id);
        $modules = Admin_module::where('status', '<>', '2')->pluck('name', 'id');
        return view('Admin.System.classify_edit', ['vo' => $res, 'modules' => $modules]);
    }

    //分类修改处理
    public function classify_edit_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                if (!$request->id) {
                    return 0;
                }
                $model = Admin_classify::find($request->id);
                if ($request->name) {
                    $model->name = $request->name;
                }
                if ($request->group_id) {
                    $model->group_id = $request->group_id;
                }
                $model->sort = $request->sort ?: 0;
                $model->route = $request->route;
                $model->func = $request->func;
                $model->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }

    //分类删除
    public function classify_del(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $res = Admin_classify::find($request->id);
                $res->status = 2;
                $res->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }


    //角色页面
    public function role()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $list = Admin_role::all();
        return view('Admin.System.role', ['menu' => __FUNCTION__, 'list' => $list]);
    }

    //角色添加页面
    public function role_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }
        return view('Admin.System.role_add');
    }

    //角色添加操作
    public function role_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $model = new Admin_role();
                $model->name = $request->role_name;
                $model->explain = $request->explain ?: '';
                $model->create_user = session()->get('account');
                $model->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }

    //分配权限
    public function role_authority($id)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $list = $this->redis['authority'];

        $arr = Admin_role_authority::where('role_id','=',$id)->get();

        foreach($list as $k => &$v){
            foreach($v['arr'] as $kk => &$vv){
                foreach($vv['arr'] as $kkk => &$vvv){
                    foreach($arr as $z => $x){
                        if($vvv['classify_id'] == $x->classify_id){
                            $vv['is_check'] = 1;
                            if($vvv['id'] == $x->authority_id){
                                $vvv['is_check'] = 1;
                            }
                        }
                    }
                }
            }
        }

        $name = Admin_role::select('name')->find($id);
        session(['role_id'=>$id]);//处理权限分配需要
        return view('Admin.System.role_authority',['list'=>$list,'name'=>$name->name]);
    }

    //处理权限分配
    public function role_authority_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if($request->ajax()){
            $post = $request->get('sub');
            $role_id = (int)session('role_id');
            $create_list = [];
            foreach($post as $k => $v){
                $m_id = $k;
                foreach($v['arr'] as $kk => $vv){
                    $c_id = $kk;
                    foreach($vv['arr'] as $kkk => $vvv){
                        $create_list[] = ['role_id'=>$role_id,'module_id'=>$m_id,'classify_id'=>$c_id,'authority_id'=>$vvv['authority_id']];
                    }
                }
            }
            DB::beginTransaction();
            try{
                Admin_role_authority::where('role_id','=',"$role_id")->delete();
                Admin_role_authority::insert($create_list);
                $this->refresh_redis('all');
            }catch(\Exception $e){
                Log::log('error',$e);
                DB::rollBack();
                return 0;
            }
            DB::commit();
            session(['role_id'=>null]);
            return 1;
        }
    }


    //角色修改页面
    public function role_edit($id)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $vo = Admin_role::find($id);

        return view('Admin.System.role_edit', ['vo' => $vo]);
    }

    //角色修改操作
    public function role_edit_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $model = Admin_role::find($request->id);
                $model->name = $request->name;
                $model->explain = $request->explain;
                $model->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }

    }

    //角色删除
    public function role_del(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $res = Admin_role::find($request->id);
                $res->status = 2;
                $res->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }

    //权限页面
    public function authority()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }


        $this->check_rule(__CLASS__,__FUNCTION__);
        $list = Admin_authority::from('admin_authority as a')
            ->join('admin_module as m','a.module_id','=','m.id')
            ->join('admin_classify as c','c.id','=','a.classify_id')
            ->select('a.*','m.name as m_name','c.name as c_name')
            ->paginate(10);
        return view('Admin.System.authority',['menu'=>__FUNCTION__,'list'=>$list]);
    }

    //权限增加页面
    public function authority_add()
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }


        $modules = Admin_module::where('status', '<>', '2')->select('name', 'id')->get();
        $classify = Admin_classify::where('status', '<>', '2')->select('name', 'id','group_id')->get();

        //拼接模块分类树状图
        $list = [];
        foreach($modules as $k => $v){
            foreach($classify as $kk => $vv){
                if($v['id'] == $vv['group_id']){
                    $list[$v['id']]['name'] = $v['name'];
                    $list[$v['id']]['arr'][$vv['id']]['id'] = $vv['id'];
                    $list[$v['id']]['arr'][$vv['id']]['name'] = $vv['name'];
                    unset($classify[$kk]);
                }
            }
        }
        return view('Admin.System.authority_add',['list'=>$list,'li'=>json_encode($list)]);
    }


    //权限增加操作
    public function authority_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }

        if ($request->ajax()) {
            try {
                $model = new Admin_authority();
                $model->module_id = $request->module_id;
                $model->classify_id = $request->classify_id;
                $model->name = $request->name;
                $model->code = $request->code;
                $model->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }
    }

    //权限修改页面
    public function authority_edit($id)
    {

        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            echo '<div style="color: #fff;text-align: center;margin-top:100px;">暂无权限</div>';
            exit;
        }

        $vo = Admin_authority::find($id);
        return view('Admin.System.authority_edit',['vo'=>$vo]);
    }


    //权限修改处理
    public function authority_edit_do(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }


        if ($request->ajax()) {
            try {
                $model = Admin_authority::find($request->id);
                $model->name = $request->name;
                $model->code = $request->code;
                $model->save();
            } catch (\Exception $e) {
                Log::log('error', $e);
                return 0;
            }
            return 1;
        }

    }

    //权限删除
    public function authority_del(Request $request)
    {
        if(!$this->check_rule(__CLASS__,__FUNCTION__)){
            return 999;
        }


        if($request->ajax()){
            try{

                $model = Admin_authority::find($request->id);
                if(0 == $model->use){
                    $model->delete();
                }
            }catch(\Exception $e){
                Log::log('error',$e);
                return 0;
            }
            return 1;
        }
    }


}
